package com.example.guetdemo.filter;

import com.alibaba.fastjson.JSON;
import com.example.guetdemo.domain.vo.UserLoginVo;
import com.example.guetdemo.enums.AppHttpCodeEnum;
import com.example.guetdemo.result.ResponseResult;
import com.example.guetdemo.utils.WebUtils;
import com.google.common.base.Splitter;
import com.example.guetdemo.domain.vo.UserVo;
import com.example.guetdemo.utils.JwtUtil;
import com.example.guetdemo.utils.RedisCache;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
@WebFilter(filterName = "JwtFilter", urlPatterns = {"/**"})
public class JwtFilter implements Filter {
    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private RedisCache redisCache;

    @Value("${filter.config.excludeUrls}")
    private String excludeUrls; // 获取配置文件中不需要过滤的uri

    private List<String> excludes;

    @Override
    public void init(FilterConfig filterConfig) {
        // 初始化
        // 加载yml配置文件中不过滤路径
        excludes = Splitter.on(",").trimResults().splitToList(this.excludeUrls);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径与请求头的token
        String uri = request.getRequestURI();
        String token = request.getHeader("token");
        String method = request.getMethod();

        try {
            if (this.isExcludesUrl(uri)) {
                //放行
                filterChain.doFilter(servletRequest,servletResponse);
            } else {
                //这个starWith记一下
                if (uri.startsWith("/websocket")) {
                    filterChain.doFilter(servletRequest,servletResponse);
                    return;
                }
                if(uri.equals("/users") && method.equals("POST")) { //总感觉这样写死是不好的，但是目前两个请求只有请求方法不同，一个需要token一个不需要token，应该如何解决，可以配置（具体的过滤器放行路径+请求方法吗）
                    filterChain.doFilter(servletRequest,servletResponse);
                    return;
                }
                if(validateParams(token)) {
                    ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
                    WebUtils.renderString(response, JSON.toJSONString(result));
                    WebUtils.setStatus(response, result.getCode());//为什么把这个放上面就不能了呢，再看看
                    return;
                }
                filterChain.doFilter(servletRequest,servletResponse);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 判断路径是否属于已经加载的放行路径，是就返回true
     * @param path
     * @return
     */
    private boolean isExcludesUrl(String path) {
        for (String v : this.excludes) {
            if (path.equals(v)) {
                return true;
            }
        }
        return false;
    }

    private boolean validateParams(String token) throws Exception {
        //解析获取userid
        Claims claims = null;
        try {
            claims = jwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //token无法解析 token超时  token非法
            return true;
        }
        String userId = claims.getSubject();
        //从redis中获取用户信息
        UserLoginVo userLoginVo = redisCache.getCacheObject("guetUser" + userId);
        //如果获取不到
        if(Objects.isNull(userLoginVo)){
            //说明登录过期  提示重新登录
            return true;
        }
        return false;
    }
}
